﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PMAF.K3Cloud.SCM.BillList.BusinessPlugIn
{
    [HotUpdate]
    [Description("销售订单列表：空单更新采购流水号")]
    public class UpdatePurchaseSn : AbstractDynamicFormPlugIn
    {
        /// <summary>
        /// 初始加载
        /// </summary>
        /// <param name="e"></param>
        public override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            //接收传递过来的单据编号
            string ids = View.OpenParameter.GetCustomParameter("ids").ToString();
            string entryIds = View.OpenParameter.GetCustomParameter("entryIds").ToString();
            //查询单据明细
            string sql = string.Format(@"/*dialect*/SELECT
                t1.FID,
                t1.FENTRYID,
                t2.FBILLNO,
                t1.FMATERIALID,
                t1.FQTY,
                t3.FNUMBER,
                t1.F_PMAF_PURCHASESN 
                FROM T_SAL_ORDERENTRY t1
                LEFT JOIN T_SAL_ORDER t2 ON t1.FID=t2.FID
                LEFT JOIN T_BD_MATERIAL t3 ON t3.FMATERIALID = t1.FMATERIALID
                WHERE t1.F_PMAF_PURCHASESN=0 AND t1.FID IN {0} AND t1.FENTRYID IN {1}", ids, entryIds);
            DynamicObjectCollection dt = DBUtils.ExecuteDynamicObject(Context, sql);
            if (dt.Count > 0)
            {
                //构建销售明细
                Entity entity = View.BillBusinessInfo.GetEntity("F_PMAF_SaleOrderEntry");
                //转换成行
                DynamicObjectCollection rows = Model.GetEntityDataObject(entity);
                //明细行索引
                int i = 0;
                foreach (DynamicObject dtRow in dt)
                {
                    //物料数据模型
                    FormMetadata materialMeta = MetaDataServiceHelper.Load(Context, "BD_Material") as FormMetadata;
                    //每行的值定义成DynamicObject
                    DynamicObject row = new DynamicObject(entity.DynamicObjectType);
                    //赋值seq
                    entity.SeqDynamicProperty.SetValue(row, i + 1);
                    //赋值第i行数据
                    row["F_PMAF_FID"] = Convert.ToInt32(dtRow["FID"]);
                    row["F_PMAF_FEntryId"] = Convert.ToInt32(dtRow["FENTRYID"]);
                    row["F_PMAF_FBillNo"] = dtRow["FBILLNO"].ToString();
                    row["F_PMAF_MaterialNo"] = dtRow["FNUMBER"].ToString();
                    int materialId = Convert.ToInt32(dtRow["FMATERIALID"]);
                    DynamicObject material = BusinessDataServiceHelper.LoadSingle(Context, materialId, materialMeta.BusinessInfo.GetDynamicObjectType());
                    row["F_PMAF_MaterialId"] = material;
                    row["F_PMAF_Qty"] = dtRow["FQTY"];
                    rows.Add(row);
                    i++;
                }
            }
        }

        /// <summary>
        /// F7选择
        /// </summary>
        /// <param name="e"></param>
        public override void BeforeF7Select(BeforeF7SelectEventArgs e)
        {
            base.BeforeF7Select(e);
            if (e.FieldKey.Equals("F_PMAF_PurchaseSn"))
            {
                //获取当前索引行
                int rowindex = View.Model.GetEntryCurrentRowIndex("F_PMAF_SaleOrderEntry");
                //当前行对应的物料编码
                DynamicObject material = (DynamicObject)View.Model.GetValue("F_PMAF_MaterialId", rowindex);
                //过滤物料为当前行的流水号
                e.ListFilterParameter.Filter = string.Format("F_PMAF_MaterialID = '{0}' AND F_PMAF_CURRENTQTY > 0", material["Id"]);
            }
        }

        /// <summary>
        /// 按钮点击
        /// </summary>
        /// <param name="e"></param>
        public override void ButtonClick(ButtonClickEventArgs e)
        {
            base.ButtonClick(e);

            //确定
            if (e.Key.Equals("F_PMAF_OKBTN"))
            {
                //构建销售明细
                Entity entity = View.BillBusinessInfo.GetEntity("F_PMAF_SaleOrderEntry");
                //转换成行
                DynamicObjectCollection rows = View.Model.GetEntityDataObject(entity);
                int purchaseCount = 0;
                StringBuilder sb = new StringBuilder();
                foreach(DynamicObject row in rows)
                {
                    int purchase = Convert.ToInt32(row["F_PMAF_PurchaseSn_Id"]);
                    if (purchase != 0)
                    {
                        purchaseCount++;
                    }
                    else
                    {
                        string note = string.Format("第{0}行流水号为空，请检查！", row["Seq"]);
                        sb.Append(note);
                    }
                }
                if (purchaseCount < rows.Count)
                {
                    e.Cancel = true;
                    View.ShowWarnningMessage(sb.ToString());
                    return;
                }
                /*
                int billId = Convert.ToInt32(rows[0]["F_PMAF_FID"]);
                //设置销售订单过滤条件并查询订单
                OQLFilter salOrderFilter = new OQLFilter
                {
                    new OQLFilterHeadEntityItem() { FilterString = string.Format("FID='{0}'", billId) }
                };
                DynamicObject[] salOrders = BusinessDataServiceHelper.Load(Context, "SAL_SaleOrder", null, salOrderFilter);
                if(salOrders.Length > 0)
                {
                    DynamicObjectCollection saleOrderEntry = (DynamicObjectCollection)salOrders[0]["SaleOrderEntry"];
                    foreach (DynamicObject item in saleOrderEntry)
                    {
                        int billEntryId = Convert.ToInt32(item["Id"]);
                        int purchaseId = Convert.ToInt32(item["F_PMAF_PurchaseSN_Id"]);
                        if(purchaseId == 0)
                        {
                            foreach (DynamicObject row in rows)
                            {
                                int dynamicEntryId = Convert.ToInt32(row["F_PMAF_FEntryId"]);

                                if(billEntryId == dynamicEntryId)
                                {
                                    item["F_PMAF_PurchaseSN_Id"] = row["F_PMAF_PurchaseSn_Id"];
                                }
                            }
                        }
                    }
                    BusinessDataServiceHelper.Save(Context, salOrders);
                }*/
                View.ReturnToParentWindow(rows);
                View.Close();
            }
        }
    }
}
